package com.tcy.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import pojo.Email;
import pojo.User;

@Configuration
public class CommonConfig {
    //注入User对象,对象默认的名字是方法名
    //如果配置文件中配置了指定的信息，则注入，否则不注入
    @ConditionalOnProperty(prefix = "country", name = {"name", "age", "gender", "phone"})
    //@Bean("aa")
    //如果方法的内部，需要使用IOC容器已经存在的bean对象，只需要在方法上声明即可，spring会自动注入
    @Bean
    public User aa(com.tcy.springbootregister.web.User user,
                   @Value("${country.name}") String name,
                   @Value("${country.age}") short age,
                   @Value("${country.gender}") short gender,
                   @Value("${country.phone}") String phone){
        System.out.println(user);
        User u = new User();
        u.setName(name);
        u.setAge(age);
        u.setGender(gender);
        u.setPhone(phone);
        return u;
    }

    @Bean
    //如果ioc容器中不存在User,则注入email,否则不注入
//    @ConditionalOnMissingBean(User.class)
    //如果当前环境中存在DispatcherServlet类，则注入Email,否则不注入
    //如果当前引入了web起步依赖，则环境中有DispatcherServlet, 否则没有
    @ConditionalOnClass(name = "org.springframework.web.servlet.DispatcherServlet")
    public Email email(){
        return new Email();
    }
}
